package core

import (
	"fmt"
	"log"
	"net/http"
	"qiuya/request"
)

func InitServer(async bool) {

	RegisterEvent(COMMAND_SHOW_DBS, func(conn *WsConn, req *request.ReqBase) *Response {
		return makeResp(ShowDBs(), nil)
	})

	RegisterEvent(COMMAND_SHOW_DBS, func(conn *WsConn) *Response {
		return makeResp(ShowDBs(), nil)
	})

	RegisterEvent(COMMAND_SHOW_COLS, func(conn *WsConn, req *request.ReqBase) *Response {
		return makeResp(ShowCols(req.DB), nil)
	})

	RegisterEvent(COMMAND_DROP_DB, func(conn *WsConn, req *request.ReqBase) *Response {
		err := DropDB(req.DB, true)
		return makeResp(err == nil, err)
	})

	RegisterEvent(COMMAND_DELETE, func(conn *WsConn, req *request.ReqDelete) *Response {
		success, err := Delete(req.DB, req.Collection, req.When)
		return makeResp(success, err)
	})

	RegisterEvent(COMMAND_INSERT, func(conn *WsConn, req *request.ReqInsert) *Response {
		success, err := InsertMany(req.DB, req.Collection, req.Data)
		return makeResp(success, err)
	})

	RegisterEvent(COMMAND_UPDATE, func(conn *WsConn, req *request.ReqUpdate) *Response {
		success, err := Update(req.DB, req.Collection, req.When, req.Then, req.Upsert)
		return makeResp(success, err)
	})

	//RegisterEvent(COMMAND_AGGREGATE, func(conn *WsConn, req *request.ReqInsert) *Response {
	//	success, err := Aggregate(req.DB, req.Collection, req.Data)
	//	return makeResp(success, err)
	//})

	RegisterEvent(COMMAND_AGGREGATE, func(conn *WsConn, req *request.ReqAggregate) *Response {
		success, err := Aggregate(req.DB, req.Collection, req.When)
		return makeResp(success, err)
	})

	RegisterEvent(COMMAND_COUNT, func(conn *WsConn, req *request.ReqCount) *Response {
		success, err := Count(req.DB, req.Collection, req.When)
		return makeResp(success, err)
	})

	RegisterEvent(COMMAND_REPLACE, func(conn *WsConn, req *request.ReqReplace) *Response {
		success, err := Replace(req.DB, req.Collection, req.When, req.Then)
		return makeResp(success, err)
	})

	//setup http server
	//serveMux := http.NewServeMux()
	http.HandleFunc("/websocket/", WebsocketHandler)
	http.Handle("/", http.FileServer(AssetFile()))

	//http.HandleFunc("/client/", )
	//log.Panic(http.ListenAndServe(":28018", serveMux))

	//_ = NewQ_object()
	//core := NewQiuya()
	//col := core.getDB("fu").getCollection("fu")
	//item:=col.GetById(123)
	//fmt.Print(item)
	//col.Insert(NewQObject())
	//core.getDB("fff").getCollection("fff").Insert()

	//http.Handle("/upper", websocket.Handler(upper))
	//http.HandleFunc("/api/insert", core.InsertHandler)
	//http.HandleFunc("/", index)

	if async {
		go listenAndServe()
	} else {
		listenAndServe()
	}
}

func makeResp(success interface{}, err error) *Response {
	if err != nil {
		return &Response{
			Code: RESP_ERROR,
			Data: err.Error(),
		}
	}
	return &Response{
		Code: RESP_OK,
		Data: success,
	}
}

func listenAndServe() {
	log.Printf("服务已启动于%d端口\n", Port)
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", Port), nil))
}
